package com.example.apidocserver.infrastructure.util;

import com.example.apidocserver.infrastructure.util.result.ParamException;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

/**
 * MD5生成工具
 *
 * @author xyqlg
 */
public class StringIdUtil {
    /**
     * string转MD5
     *
     * @param str 入参
     * @return 返回参数
     */
    public static String toMd5(String str) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] messageDigest = md.digest(str.getBytes());
            StringBuilder hexString = new StringBuilder();
            for (byte b : messageDigest) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            throw new ParamException("参数错误。");
        }
    }

    /**
     * 生成uuid
     *
     * @return uuid
     */
    public static String generateUUID() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }
}
